import time

from .time_tasks import scheduler, task_func_list
from flask import request, g, json
from utils.common import response_get, response_other, response_error, get_body_data


# 获取任务函数列表
def get_task_func_list():
    task_funcs = []
    for item in task_func_list:
        task_funcs.append({"func_name": item['title'], "func_role": item['role']})
    return response_get(data=task_funcs)


# 添加任务 删除任务 修改任务 查
def task():
    method = request.method
    if method == 'GET':
        task_id = request.args.get('task_id') or None
        if task_id:
            job = scheduler.get_job('task_id')
            print(job)
            # 查找数数据库
            result = g.db_1.find('task', '*', f'task_id = {task_id}')
            if type(result) == list:
                return response_get(data=result)
            elif result == 'error':
                return response_error(500)
            else:
                return response_get()
        else:
            result = g.db_1.find('task')
            return response_get(data=result)
    elif method == 'POST':
        body_data = get_body_data()
        data_params = [
            'task_params',
            'task_name',
            'task_func_name',
            'task_type'
        ]
        for param in data_params:
            if param not in body_data:
                return response_error()
        try:
            task_params = dict(body_data.pop('task_params'))
        except:
            return response_error()

        task_name = body_data.pop('task_name')
        task_type = body_data.pop('task_type')
        task_func_name = body_data.pop('task_func_name')
        task_func = None
        for task_item in task_func_list:
            if task_item['title'] == task_func_name:
                task_func = task_item['func']
        if not task_func:
            return response_error(err_msg="找不到任务函数!")
        task_id = str(round(time.time(), 4))
        try:
            scheduler.add_job(task_id, name=task_name,args=(task_id,task_name) ,func=task_func, trigger=task_type, **task_params)
            scheduler.pause_job(task_id)
            result = g.db_1.add('task',
                                {"task_name": task_name, "task_type": task_type, "task_func_name": task_func_name,
                                 "task_params": str(task_params), "task_id": task_id})
            if result != 'error':
                return response_other()
        except Exception as e:
            print(e)
            return response_error(500, "添加任务失败!")

    elif method == 'PUT':
        # 修改任务
        body_data1 = get_body_data()
        if not body_data1:
            return response_error()
        data_params = [
            'task_params',
            'task_name',
            'task_func_name',
            'task_type',
            'task_id',
            'state',
        ]
        body_data = {}
        for key,value in body_data1.items():
            # key 如果在,值也在 添加到对象中
            if key in data_params and value:
                body_data.setdefault(key,value)
        if 'task_id' not in body_data or 'state' not in body_data:
            return response_error()
        task_id = body_data['task_id']
        state = body_data['state']
        if state != 'start' and state != 'end':
            return response_error(err_msg="state错误")
        # 更新任务
        result = g.db_1.update('task', body_data, f'task_id = {task_id}')
        if result == 'error':
            return response_error()
        # 将原先的任务删掉
        try:
            scheduler.remove_job(task_id)
        except Exception as e:
            print(e)
            return response_error(err_msg='找不到任务!')
        # 读取任务
        result = g.db_1.find('task','*',f'task_id = {task_id}')
        if type(result) == list:
            task_func_name = result[0]['task_func_name']
            task_name = result[0]['task_name']
            task_type = result[0]['task_type']
            # 转换为字典
            task_params = eval(result[0]['task_params'])
            # 添加任务
            task_func = None
            for task_item in task_func_list:
                if task_item['title'] == task_func_name:
                    task_func = task_item['func']
            if not task_func:
                return response_error(err_msg="找不到任务函数!")
            # 添加任务
            scheduler.add_job(task_id, name=task_name,args=(task_id,task_name) ,func=task_func, trigger=task_type, **task_params)
            if state == 'end':
                # 暂停任务
                scheduler.pause_job(task_id)
            return response_other()
        if result == 'ok':
            return response_other()

    elif method == 'DELETE':
        body_data = get_body_data()
        if not body_data:
            return response_error()
        if 'task_id' not in body_data:
            return response_error()
        task_id = body_data.pop('task_id')
        result = g.db_1.delete('task', f'task_id = {task_id}')
        # 删除任务
        scheduler.remove_job(task_id)
        if result == 'ok':
            return response_other()

    return response_error()
